package com.oj.friend.manager;

import cn.hutool.core.bean.BeanUtil;
import com.oj.common.core.constants.CacheConstants;
import com.oj.common.core.enums.ResultCode;
import com.oj.common.redis.service.RedisService;
import com.oj.common.security.exception.ServiceExpection;
import com.oj.friend.domain.user.User;
import com.oj.friend.domain.user.vo.LoginUserInfo;
import com.oj.friend.mapper.UserMapper;
import jakarta.annotation.Resource;
import jakarta.annotation.Resources;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Author bin
 * @Date 2025/6/11
 */

@Component
public class UserCacheManager {

    @Resource
    private RedisService redisService;

    @Resource
    private UserMapper userMapper;

    private static final Long EXP = 10L;
    public LoginUserInfo getUserById(Long userId) {
        String key = getUserKey(userId);
        LoginUserInfo loginUserInfo = redisService.getCacheObject(key, LoginUserInfo.class);
        if (loginUserInfo == null) {
            User user = userMapper.selectById(userId);
            if(user == null){
                throw new ServiceExpection(ResultCode.FAILED_USER_NOT_EXISTS);
            }
            loginUserInfo = new LoginUserInfo();
            BeanUtil.copyProperties(user,loginUserInfo);
            // 存到redis中10分钟
            refreshLoginUserInfo(loginUserInfo);
            return loginUserInfo;
        } else {
            //延长至10分钟
            redisService.setCacheObject(getUserKey(loginUserInfo.getUserId()), loginUserInfo, EXP, TimeUnit.MINUTES);
            return loginUserInfo;
        }
    }

    private void refreshLoginUserInfo(LoginUserInfo loginUserInfo) {
        redisService.setCacheObject(getUserKey(loginUserInfo.getUserId()), loginUserInfo, EXP, TimeUnit.MINUTES);
    }


    private String getUserKey(Long userId) {
        return CacheConstants.USER_DETAIL_KEY + userId;
    }

    public void refreshUser(User user) {
        Long userId = user.getUserId();
        redisService.deleteObject(CacheConstants.USER_DETAIL_KEY + userId);
        redisService.setCacheObject(CacheConstants.USER_DETAIL_KEY + userId, user);
    }
}
